let upload = require('./fileUpload');
const crypto = require('crypto');
const async = require('async');
const secret = 'abcdef';
const log4js = require('./log4js');
const logger = log4js.getLogger('uplogs');
const sequelize = require('./sequelize');
const Sequelize = require('sequelize');
const Image = sequelize.define('image',{
    imgId:{ type: Sequelize.BIGINT(11), autoIncrement: true,primaryKey:true},
    key:Sequelize.STRING,
    pixivId:Sequelize.BIGINT(11)
},{
    timestamps:false,
    freezeTableName:true,
});
const Pixiv = sequelize.define('pixiv',{
    pixivId:{ type: Sequelize.BIGINT(11), autoIncrement: true,primaryKey:true},
    title:Sequelize.STRING,
    fileName:Sequelize.STRING,
    userName:Sequelize.STRING,
    imgCount:Sequelize.INTEGER,
    tag:Sequelize.STRING,
    uploadTime:Sequelize.BIGINT(11),
    oldId:Sequelize.BIGINT(11),
    userId:Sequelize.BIGINT(11),
    collectNum:Sequelize.BIGINT(11),
    step:{type:Sequelize.BOOLEAN,defaultValue:1},
    url:Sequelize.STRING
},{
    timestamps:false,
    freezeTableName:true,
});
//初始化上传配置项
upload.getUploadConf();
async function uploadController(fileStr = '',id = '') {
    return new Promise((resolve,reject) =>{
        upload.createOptions(fileStr,id);
        let _temp = fileStr.split(".");
        let fileName = crypto.createHash('md5', secret).update(`pixiv-${new Date().getTime()}-master`).digest('hex')+'.'+_temp[_temp.length-1];
        upload.upload(fileName).then(res =>{
            if(res.statusCode === 200) {
                Image.create({key:fileName,pixivId:id}).then(() =>{
                    logger.info(`${id} 写入数据库成功`);
                }).catch(err =>{
                    logger.error(`${id} 写入数据库失败:${err}`);
                });
            }else{
                logger.error(`${id} 上传失败`);
            }
            resolve();
        }).catch(err =>{
            logger.error(`${id} 上传失败:err`);
            reject();
        });
    });
}
let i = 0;
// uploadController('2012/01/14/08/56/15/24360118.jpg',24360118,1,{hashName:true});
async function init() {
    let res = await Pixiv.findOne({where:{step:1}, attributes:['pixivId','fileName','imgCount','oldId','downloadUrl']});
    let {fileName,oldId,imgCount,pixivId,downloadUrl} = res.dataValues;
    if(imgCount > 1){
        downloadUrl = JSON.parse(downloadUrl);
        for (let i = 0;i<downloadUrl.length;i++){
            await uploadController(downloadUrl[i],oldId);
        }
    }else{
        await uploadController(fileName,oldId);
    }
    await update(pixivId);
    logger.info(`${i} 条写入成功`);
    init();
}
async function update(pixivId){
    return Pixiv.update({step:2},{where:{pixivId}});
}
init();